<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\client;

use app\model\ClientAccountModel;
use app\model\KsAdvertiserModel;
use app\service\BaseService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

final class KuaiShouAccountService extends BaseService
{
    /**
     * 获取快手user_id.
     * @param string $advertiserId 账户id
     * @return mixed
     */
    public static function getKsUserId(string $advertiserId = '')
    {
        $where = [
            ['advertiser_id', '=', $advertiserId],
        ];
        return (new KsAdvertiserModel())->where($where)->value('user_id');
    }

    /**
     * 获取不同user-id下广告主id.
     * @return mixed
     */
    public static function getKsUserAdvertiserIds()
    {
        return (new KsAdvertiserModel())->group('user_id')->select();
    }

    /**
     * 根据userId获取账户id.
     *
     * @param string $userId 用户id
     * @return array|bool
     */
    public function getAdvertiserByUserId(string $userId = '')
    {
        if (! $userId) {
            return self::setError('未知快手用户id');
        }
        return (new KsAdvertiserModel())->where('user_id', $userId)->column('advertiser_id');
    }

    /**
     * 根据userId获取客户列表.
     * @param string $userId 用户id
     * @return array|bool|ClientAccountModel[]|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getClientAdvertiserByUserId(string $userId = '')
    {
        if (! $userId) {
            return self::setError('未知快手用户id');
        }

        return (new ClientAccountModel())->where('advertiser_id', 'in', function ($query) use ($userId) {
            $query->table((new KsAdvertiserModel())->getTable())->where('user_id', $userId)->field('advertiser_id');
        })->select();
    }
}
